<template>
  <div class="view-fill">
    <div v-if="!showModify.visible" class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :btn-list="btnList"
        :title="title"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <el-button v-if="canReceiveOrder" @click="receiveOrder"
            >接单</el-button
          >
          <el-button v-if="canTurnOver" @click="turnOver">转交</el-button>
          <el-button v-if="canHandleRegister" @click="handleRegister"
            >处理登记</el-button
          >
          <el-button v-if="canFinish" @click="finish">完工</el-button>
          <el-button v-if="canFaultVerify" @click="faultVerify"
            >故障确认</el-button
          >
          <el-button v-if="canMountingsUse" @click="mountingsUse"
            >配件使用</el-button
          >
          <el-button v-if="canCancelFinish" @click="cancelFinish"
            >取消完工</el-button
          >
        </template>

        <div class="model-panel model-panel-left">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <basic-information
              :info="baseInfoList"
              :image-field="baseInfoList.imageField"
            ></basic-information>
          </div>
        </div>

        <div class="model-panel model-panel-left">
          <div class="model-panel-title">
            <p>故障信息</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="faultInfoList"> </basic-information>
          </div>
        </div>
        <div class="model-panel model-panel-left">
          <div class="model-panel-title">
            <p>派单信息</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="sendOrderInfoList"> </basic-information>
          </div>
        </div>

        <div class="model-panel model-panel-left">
          <div class="model-panel-title">
            <p>完工信息</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="finishInfoList"></basic-information>
          </div>
        </div>

        <div class="model-panel model-panel-left">
          <div class="model-panel-body">
            <div class="flex_full_item">
              <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane
                  class="model-panel-title"
                  label="处理记录"
                  name="first"
                >
                  <!-- 表格 -->
                  <el-form
                    ref="tableForm"
                    :model="dealInfo"
                    style="width: 100%"
                  >
                    <page-table
                      :refresh="dealInfo.refresh"
                      :init-curpage="dealInfo.initCurpage"
                      v-model:data="dealInfo.data"
                      :pager="false"
                      :check-box="false"
                      :tab-index="true"
                      :api="dealInfo.api"
                      :query="dealInfo.query"
                      :field-list="dealInfo.fieldList"
                      :isDynamic="true"
                    >
                      <template v-slot:col-filePathList="scope">
                        <UploadList
                          v-if="scope.row.filePathList"
                          :fileData="scope.row.filePathList"
                          :uploadDisabled="false"
                        />
                        <span v-else>-</span>
                      </template>
                    </page-table>
                  </el-form>
                </el-tab-pane>
                <el-tab-pane
                  class="model-panel-title"
                  label="配件使用"
                  name="second"
                >
                  <!-- 表格 -->
                  <page-table
                    :refresh="mountingsUseTableInfo.refresh"
                    :init-curpage="mountingsUseTableInfo.initCurpage"
                    v-model:data="mountingsUseTableInfo.data"
                    :pager="false"
                    :check-box="false"
                    :tab-index="true"
                    :api="mountingsUseTableInfo.api"
                    :query="mountingsUseTableInfo.query"
                    :field-list="mountingsUseTableInfo.fieldList"
                    :isDynamic="true"
                  />
                </el-tab-pane>
                <el-tab-pane
                  class="model-panel-title"
                  label="完工记录"
                  name="third"
                >
                  <!-- 表格 -->
                  <page-table
                    :refresh="finishTableInfo.refresh"
                    :init-curpage="finishTableInfo.initCurpage"
                    v-model:data="finishTableInfo.data"
                    :pager="false"
                    :check-box="false"
                    :tab-index="true"
                    :api="finishTableInfo.api"
                    :query="finishTableInfo.query"
                    :field-list="finishTableInfo.fieldList"
                    :isDynamic="true"
                  />
                </el-tab-pane>
              </el-tabs>
            </div>
          </div>
        </div>

        <div class="model-panel model-panel-right">
          <div class="model-panel-body">
            <div class="flex_full_item">
              <el-tabs v-model="clickName" @tab-click="handleTabClick">
                <el-tab-pane
                  class="model-panel-title"
                  label="基本信息"
                  name="first"
                >
                  <basic-information :info="basicInfoList"></basic-information>
                </el-tab-pane>
                <el-tab-pane
                  class="model-panel-title"
                  label="报修详情"
                  name="second"
                >
                  <basic-information :info="repairInfoList">
                    <template v-slot:basic-filePathList>
                      <UploadVideo
                        :fileData="repairInfoList.data.filePathList"
                        :uploadDisabled="false"
                      /> </template
                  ></basic-information>
                </el-tab-pane>
                <el-tab-pane
                  class="model-panel-title"
                  label="操作流水"
                  name="third"
                >
                  <Timeline :list="affairTableInfo.data" />
                </el-tab-pane>
              </el-tabs>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <!-- 转交 -->
    <page-dialog
      v-show="turnOverInfo.visible"
      :title="turnOverInfo.title"
      v-model:visible="turnOverInfo.visible"
      :width="turnOverInfo.width"
      :bt-loading="turnOverInfo.btLoading"
      :bt-list="turnOverInfo.btList"
    >
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="turnOverInfo.formInfo.ref"
        :data="turnOverInfo.formInfo.data"
        :field-list="turnOverInfo.formInfo.fieldList"
        :rules="turnOverInfo.formInfo.rules"
        :label-width="turnOverInfo.formInfo.labelWidth"
      >
        <template v-slot:form-acceptUserName>
          <el-input
            type="input"
            :disabled="true"
            class="not-mongolia"
            placeholder="请选择维修人员"
            v-model="turnOverInfo.formInfo.data.acceptUserName"
          >
            <template #append>
              <el-icon @click="openRepairUserWindow"><MoreFilled /></el-icon>
            </template>
          </el-input>
        </template>
      </page-form>
    </page-dialog>
    <!-- 维修人员 -->
    <SelectRepairUser
      v-if="selectRepairUserInfo.visible"
      v-model:showDialog="selectRepairUserInfo.visible"
      :check-box="false"
      :saveEmpty="true"
      :highlight-row="true"
      :api="selectRepairUserInfo.api"
      :query="selectRepairUserInfo.query"
      @callback="selectRepairUserCallBack"
    />
    <!-- 处理登记 -->
    <page-dialog
      v-show="registerInfo.visible"
      :title="registerInfo.title"
      v-model:visible="registerInfo.visible"
      :width="registerInfo.width"
      :bt-loading="registerInfo.btLoading"
      :bt-list="registerInfo.btList"
    >
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="registerInfo.formInfo.ref"
        :data="registerInfo.formInfo.data"
        :field-list="registerInfo.formInfo.fieldList"
        :rules="registerInfo.formInfo.rules"
        :label-width="registerInfo.formInfo.labelWidth"
      >
        <template v-slot:form-startTime>
          <el-date-picker
            v-model="registerInfo.formInfo.data.startTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
            placeholder="请选择开始时间"
          >
          </el-date-picker>
        </template>
        <template v-slot:form-endTime>
          <el-date-picker
            v-model="registerInfo.formInfo.data.endTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
            placeholder="请选择结束时间"
          >
          </el-date-picker>
        </template>
        <template v-slot:form-filePathList>
          <el-upload
            :headers="registerInfo.uploadInfo.headers"
            :on-error="uploadError"
            :on-success="uploadAttachment"
            :on-remove="uploadRemove"
            :before-upload="beforeProductUpload"
            :on-exceed="handleExceed"
            :action="registerInfo.uploadInfo.action"
            :limit="registerInfo.uploadInfo.limit"
            :file-list="registerInfo.uploadInfo.fileList"
          >
            <el-button>点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              文件大小不超过{{
                $store.state.permission.systemConfig.max_file_size
              }}M
            </div>
          </el-upload>
        </template>
      </page-form>
    </page-dialog>
    <!-- 完工 -->
    <page-dialog
      v-show="finishInfo.visible"
      :title="finishInfo.title"
      v-model:visible="finishInfo.visible"
      :width="finishInfo.width"
      :bt-loading="finishInfo.btLoading"
      :bt-list="finishInfo.btList"
    >
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="finishInfo.formInfo.ref"
        :data="finishInfo.formInfo.data"
        :field-list="finishInfo.formInfo.fieldList"
        :rules="finishInfo.formInfo.rules"
        :label-width="finishInfo.formInfo.labelWidth"
      >
        <template v-slot:form-completeTime>
          <el-date-picker
            v-model="finishInfo.formInfo.data.completeTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
            placeholder="选择日期"
          >
          </el-date-picker>
        </template>
      </page-form>
    </page-dialog>
    <!-- 故障确认 -->
    <page-dialog
      v-show="faultVerifyInfo.visible"
      :title="faultVerifyInfo.title"
      v-model:visible="faultVerifyInfo.visible"
      :width="faultVerifyInfo.width"
      :bt-loading="faultVerifyInfo.btLoading"
      :bt-list="faultVerifyInfo.btList"
    >
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="faultVerifyInfo.formInfo.ref"
        :data="faultVerifyInfo.formInfo.data"
        :field-list="faultVerifyInfo.formInfo.fieldList"
        :rules="faultVerifyInfo.formInfo.rules"
        :label-width="faultVerifyInfo.formInfo.labelWidth"
      >
        <template v-slot:form-faultTime>
          <el-date-picker
            v-model="faultVerifyInfo.formInfo.data.faultTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </template>
        <template v-slot:form-faultPart>
          <el-input
            v-model="faultVerifyInfo.formInfo.data.faultPart"
            type="input"
            class="not-mongolia"
            placeholder="请输入/选择故障部位"
          >
            <template #append>
              <el-icon @click="openAssetResource"><MoreFilled /></el-icon>
            </template>
          </el-input>
        </template>
        <template v-slot:form-faultDescribe>
          <el-input
            :style="{
              width: $permission('repairOrder:selectFaultLib') ? '86%' : '100%',
            }"
            v-model="faultVerifyInfo.formInfo.data.faultDescribe"
            type="textarea"
            :rows="1"
            class="not-mongolia"
            placeholder="请输入故障描述"
          >
          </el-input>
          <el-tooltip
            v-if="$permission('repairOrder:selectFaultLib')"
            effect="dark"
            content="从故障库选择"
            placement="top-start"
          >
            <el-icon style="font-size: 20px; cursor: pointer" @click="openFault"
              ><CirclePlus
            /></el-icon>
          </el-tooltip>
        </template>
        <template v-slot:form-maintenanceScheme>
          <el-input
            :style="{
              width: $permission('maintenanceOrder:addFaultLib')
                ? '86%'
                : '100%',
            }"
            v-model="faultVerifyInfo.formInfo.data.maintenanceScheme"
            type="textarea"
            :rows="1"
            class="not-mongolia"
            placeholder="请输入维修方案"
          >
          </el-input>
          <el-tooltip
            v-if="$permission('maintenanceOrder:addFaultLib')"
            effect="dark"
            content="加入故障库"
            placement="top-start"
          >
            <el-icon style="font-size: 20px; cursor: pointer" @click="_addFault"
              ><CirclePlus
            /></el-icon>
          </el-tooltip>
        </template>
      </page-form>
    </page-dialog>
    <!-- 配件使用 -->
    <page-dialog
      v-show="mountingsUseInfo.visible"
      :title="mountingsUseInfo.title"
      v-model:visible="mountingsUseInfo.visible"
      :width="mountingsUseInfo.width"
      :bt-loading="mountingsUseInfo.btLoading"
      :bt-list="mountingsUseInfo.btList"
    >
      <NewPageFilter
        v-model:query="mountingsUseInfo.filterInfo.query"
        :filter-btn="mountingsUseInfo.filterInfo.list"
      >
        <template v-slot:filter-removeMountings>
          <el-button
            :disabled="!mountingsUseInfo.tableInfo.selections.length"
            @click="removeMountings(undefined)"
            >删除</el-button
          >
        </template>
      </NewPageFilter>
      <el-form
        :model="mountingsUseInfo.tableInfo"
        ref="tableForm"
        style="width: 100%"
      >
        <!-- 表格 -->
        <dialog-table
          ref="mountingsUseTable"
          :refresh="mountingsUseInfo.tableInfo.refresh"
          :init-curpage="mountingsUseInfo.tableInfo.initCurpage"
          v-model:data="mountingsUseInfo.tableInfo.data"
          :api="mountingsUseInfo.tableInfo.api"
          :query="mountingsUseInfo.tableInfo.query"
          :pager="true"
          :tabIndex="true"
          :field-list="mountingsUseInfo.tableInfo.fieldList"
          :handle="mountingsUseInfo.tableInfo.handle"
          :row-class-name="mountingsUseInfo.tableRowClassName"
          @handleEvent="selectMountingsTable"
        >
          <template v-slot:col-price="scope">
            <el-form-item
              :prop="`data.${scope.$index}.price`"
              :rules="
                scope.$index >= 0
                  ? [
                      {
                        validator: $validate.positiveMoneyNoZeroAsset,
                        trigger: ['blur', 'change'],
                      },
                      {
                        required: scope.$index >= 0,
                        message: '请输入单价',
                        trigger: 'blur',
                      },
                    ]
                  : []
              "
            >
              <el-input-number
                style="width: 100%; margintop: 18px"
                v-model.lazy="scope.row.price"
                clearable
                controls-position="right"
                :precision="
                  $store.state.permission.systemConfig.assets_price_precision
                "
                @change="changePrice($event, scope.row, `price`)"
                :min="0"
                :max="999999999999999"
              />
            </el-form-item>
          </template>
          <template v-slot:col-qty="scope">
            <el-form-item
              :prop="`data.${scope.$index}.qty`"
              :rules="
                scope.$index >= 0
                  ? [
                      {
                        validator: $validate.positiveNoAsset,
                        trigger: ['blur', 'change'],
                      },
                      {
                        required: scope.$index >= 0,
                        message: '请输入数量',
                        trigger: 'blur',
                      },
                    ]
                  : []
              "
            >
              <el-input-number
                style="width: 100%; margintop: 18px"
                v-model.lazy="scope.row.qty"
                clearable
                controls-position="right"
                :precision="2"
                @change="changePrice($event, scope.row, `qty`)"
                :min="0"
                :max="999999999999999"
              />
            </el-form-item>
          </template>
          <template v-slot:col-useTime="scope">
            <el-form-item
              :prop="`data.${scope.$index}.useTime`"
              :rules="
                scope.$index >= 0
                  ? [
                      {
                        validator: validateUseTime,
                        trigger: 'blur',
                      },
                    ]
                  : []
              "
            >
              <el-date-picker
                v-model="scope.row.useTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择日期"
              ></el-date-picker>
            </el-form-item>
          </template>
        </dialog-table>
      </el-form>
    </page-dialog>
    <!-- 选择配件 -->
    <SelectAccessories
      v-if="accessoriesInfo.visible"
      v-model:show-dialog="accessoriesInfo.visible"
      :query="accessoriesInfo.query"
      @callback="changeAccessories"
    />
    <Select-fault
      v-if="seelctFault.visible"
      v-model:show-dialog="seelctFault.visible"
      :query="seelctFault.query"
      :check-box="false"
      :saveEmpty="true"
      :highlight-row="true"
      @callback="selectFaultCallback"
    />
    <add-fault
      v-if="tableDialogInfo.visible"
      v-model:show-dialog="tableDialogInfo.visible"
      :data="tableDialogInfo.data"
      @callback="addFaultCallback"
    />
    <SelectAssetResource
      v-if="selectAssetResourceInfo.visible"
      v-model:showDialog="selectAssetResourceInfo.visible"
      :query="selectAssetResourceInfo.query"
      :saveEmpty="true"
      :check-box="true"
      :highlight-row="false"
      @callback="SelectAssetResourceCallBack"
    />
  </div>
</template>

<script setup name="MaintenanceOrderDetails">
import BasicInformation from '@/components/BasicInformation/index'
import Timeline from '@/components/Timeline/index.vue'
import UploadVideo from '@/components/UploadVideo/index'
import {
  delByMaintenanceIdRepairPartsAffair,
  getRepairPartsAffairPage,
  cannelMaintenceOrder,
  createRepairPartsAffair,
  faultConfirmMaintenceOrder,
  dealCompleteMaintenceOrder,
  repairDealAffair,
  passOnMaintenceOrder,
  acceptMaintenceOrder,
  getRepairOrderById,
  getRepairPartsAffairAll,
  getRepairDealAffairAll,
  getMaintenceOrderById,
  getRepairCompleteAffairAll,
  getMaintenanceGroupsUserPage,
  getSelectUserWithPermission,
  summaryWorkingHours,
  getMaintenceOrderCustomizeListAll,
} from '@/api/repair'
import { getCustomizeSetting } from '@/api/customize'
import PageTable from '@/components/PageTable'
import { orderOpAffairAll } from '@/api/affair'
import SelectRepairUser from '@/components/SelectUsers/selectMaintenanceUsers'
import SelectAccessories from '@/components/SelectAccessories/index'
import selectAsset from '@/components/SelectAsset/index'
import UploadList from '@/components/UploadVideo/uploadList'

import PageDialog from '@/components/PageDialog/index'
import PageForm from '@/components/PageForm/index'
import DialogTable from '@/components/DialogTable/index'

import addFault from './addFault.vue'

import { ElLoading, ElMessage } from 'element-plus'
import axios from 'axios'
import moment from 'moment'

const { proxy } = getCurrentInstance()
const emit = defineEmits()

const props = defineProps(['visible', 'id'])

let validateFaultTime = (rule, value, callback) => {
  let currentTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
  if (value > currentTime) {
    callback(new Error('故障发生时间不能大于当前时间！'))
  } else {
    callback()
  }
}
let validateCompleteTime = (rule, value, callback) => {
  let currentTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
  if (value > currentTime) {
    callback(new Error('完工时间不能大于当前时间！'))
  } else {
    callback()
  }
}
let validateStartTime = (rule, value, callback) => {
  let endTime = registerInfo.formInfo.data.endTime
  if (endTime) {
    if (endTime < value) {
      callback(new Error('开始时间不能大于结束时间！'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}
let validateEndTime = (rule, value, callback) => {
  let startTime = registerInfo.formInfo.data.startTime
  if (startTime) {
    if (startTime > value) {
      callback(new Error('结束时间不能小于开始时间！'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}
const tableDialogInfo = ref({
  data: {},
  visible: false,
  type: '',
})
const seelctFault = ref({
  visible: false,
  query: {},
})
const clickItem = ref({})
const assetSourceAuth = ref(false)
const activeName = ref('first')
const clickName = ref('first')
const title = ref('维修单详情')
const btnList = ref([])
//基础信息
const baseInfoList = reactive({
  data: [],
  fieldList: [
    {
      label: '维修单号',
      value: 'orderNo',
      type: 'text',
    },
    {
      label: '维修人',
      value: 'maintenanceUserName',
      type: 'text',
    },

    {
      label: '状态',
      value: 'statusValue',
      type: 'text',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'popover',
    },
  ],
})
//故障信息
const faultInfoList = reactive({
  data: [],
  fieldList: [
    {
      label: '资产',
      value: 'assetName',
      type: 'text',
    },
    {
      label: '资产卡片号',
      value: 'assetCode',
      type: 'text',
    },
    {
      label: '故障发生时间',
      value: 'faultTime',
      type: 'text',
    },
    {
      label: '停机时长(h)',
      value: 'haltTime',
      type: 'text',
    },
    {
      label: '故障部位',
      value: 'faultPart',
      type: 'text',
    },
    {
      label: '故障描述',
      value: 'faultDescribe',
      type: 'popover',
    },
    {
      label: '故障原因',
      value: 'faultReason',
      type: 'popover',
    },
    {
      label: '维修方案',
      value: 'maintenanceScheme',
      type: 'popover',
    },
  ],
})
//派单信息
const sendOrderInfoList = reactive({
  data: [],
  fieldList: [
    {
      label: '派单人',
      value: 'dispatchUserName',
      type: 'text',
    },
    {
      label: '派单给',
      value: 'pendReceiveUserName',
      type: 'text',
    },
    {
      label: '派单时间',
      value: 'dispatchTime',
      type: 'text',
    },
    {
      label: '要求完成时间',
      value: 'requireCompleteTime',
      type: 'text',
    },
    {
      label: '派单说明',
      value: 'dispatchDescribe',
      type: 'popover',
    },
  ],
})
//完工信息
const finishInfoList = reactive({
  data: [],
  fieldList: [
    {
      label: '处理结果',
      value: 'dealResultValue',
      type: 'text',
    },
    // {
    //   label: '完工时间',
    //   value: 'completeTime',
    //   type: 'text',
    // },
    {
      label: '处理工时(h)',
      value: 'dealTime',
      type: 'text',
    },
    {
      label: '维修材料费(元)',
      value: 'materialAmount',
      type: 'text',
    },
    {
      label: '维修服务费(元)',
      value: 'serviceAmount',
      type: 'text',
    },
    // {
    //   label: '完工说明',
    //   value: 'dealDescribe',
    //   type: 'text',
    // },
  ],
})
//基本信息
const basicInfoList = reactive({
  data: [],
  fieldList: [
    {
      label: '维修单号',
      value: 'orderNo',
      type: 'text',
    },
    {
      label: '状态',
      value: 'statusValue',
      type: 'text',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'text',
    },
    {
      label: '创建人',
      value: 'createUserName',
      type: 'text',
    },
    {
      label: '创建时间',
      value: 'createTime',
      type: 'text',
    },
    {
      label: '最后更新人',
      value: 'updateUserName',
      type: 'text',
    },
    {
      label: '最后更新时间',
      value: 'updateTime',
      type: 'text',
    },
  ],
})
//报修信息
const repairInfoList = reactive({
  data: [],
  fieldList: [
    {
      label: '报修单号',
      value: 'orderNo',
      type: 'text',
    },
    {
      label: '报修人',
      value: 'repairUserName',
      type: 'text',
    },
    {
      label: '报修人电话',
      value: 'repairUserTel',
      type: 'text',
    },
    {
      label: '资产',
      value: 'assetName',
      type: 'text',
    },
    {
      label: '资产卡片号',
      value: 'assetCode',
      type: 'text',
    },
    {
      label: '资产分类',
      value: 'classifyTypeValue',
      type: 'text',
    },
    {
      label: '维修类别',
      value: 'notAssetRepairTypeValue',
      type: 'text',
    },
    {
      label: '使用部门',
      value: 'useDeptName',
      type: 'text',
      show: true,
    },
    {
      label: '仓库',
      value: 'depotName',
      type: 'text',
      show: false,
    },
    {
      label: '资产位置',
      value: 'location',
      type: 'text',
    },
    {
      label: '紧急程度',
      value: 'urgencyDegreeName',
      type: 'text',
    },
    {
      label: '是否停机',
      value: 'isHaltName',
      type: 'text',
    },
    {
      label: '故障部位',
      value: 'faultPart',
      type: 'text',
    },
    {
      label: '故障发生时间',
      value: 'faultTime',
      type: 'text',
    },
    {
      label: '期望完成时间',
      value: 'expectCompleteTime',
      type: 'text',
    },
    {
      label: '故障描述',
      value: 'faultDescribe',
      type: 'popover',
    },
    {
      label: '故障图片/视频',
      value: 'filePathList',
      type: 'slot',
      className: 'not-br',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'text',
    },
  ],
})
// 过滤相关配置
const filterInfo = reactive({
  query: {
    productId: props.id,
    sort: 'is_default desc,create_time desc',
  },
  list: [],
})
// 处理记录
const dealInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  api: getRepairDealAffairAll,
  data: [],
  query: {
    orderType: 54,
    orderId: '',
    sort: 'create_time desc',
  },
  fieldList: [
    { label: '处理人', value: 'dealUserName' },
    { label: '开始时间', value: 'startTime' },
    { label: '结束时间', value: 'endTime' },
    { label: '处理进度(%)', value: 'dealRate' },
    { label: '工作说明', value: 'dealDescribe' },
    { label: '附件', value: 'filePathList', type: 'slot' },
  ],
})
// 配件使用记录
const mountingsUseTableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  api: getRepairPartsAffairAll,
  data: [],
  query: {
    maintenanceOrderId: props.id,
    sort: 'create_time desc',
  },
  fieldList: [
    { label: '使用配件', value: 'commonName' },
    { label: '规格', value: 'standard' },
    { label: '计量单位', value: 'unitName' },
    { label: '单价', value: 'price' },
    { label: '数量', value: 'qty' },
    { label: '金额', value: 'sumAmount' },
    { label: '更换日期', value: 'useTime' },
    // { label: "备注", value: "remark" },
  ],
})

const finishTableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  api: getRepairCompleteAffairAll,
  data: [],
  query: {
    maintenanceId: props.id,
    sort: 'create_time desc',
  },
  fieldList: [
    {
      label: '处理结果',
      value: 'dealResultValue',
      type: 'text',
    },
    {
      label: '完工时间',
      value: 'completeTime',
      type: 'text',
    },
    {
      label: '处理工时(h)',
      value: 'dealTime',
      type: 'text',
    },
    {
      label: '维修材料费(元)',
      value: 'materialAmount',
      type: 'text',
    },
    {
      label: '维修服务费(元)',
      value: 'serviceAmount',
      type: 'text',
    },
    {
      label: '完工说明',
      value: 'dealDescribe',
      type: 'text',
    },
  ],
})

// 操作流水
const affairTableInfo = reactive({
  data: [],
  query: {
    orderType: 54,
    orderId: props.id,
    sort: 'operate_time desc',
  },
})
// 过滤相关配置
const customFilterInfo = reactive({
  query: {
    queryMap: {
      id: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id,
      },
    },
    queryParams: {
      isAssetAchievesExcel: 'true',
    },
  },
})
const showModify = reactive({
  title: '修改',
  type: 'update',
  visible: false,
  currentAccountingInterval: '',
})
//转交相关
const turnOverInfo = reactive({
  visible: false,
  title: '',
  btLoading: false,
  type: '',
  msg: '',
  width: '40%',
  flag: true,
  btList: [
    {
      label: '关闭',
      event: handleCloseTurnOver,
      show: true,
    },
    {
      label: '保存',
      type: 'primary',
      event: saveTurnOver,
      show: true,
    },
  ],

  formInfo: {
    ref: null,
    data: {},
    fieldList: [
      {
        label: '转交给',
        value: 'acceptUserName',
        type: 'slot',
        required: true,
      },
      {
        label: '转交说明',
        value: 'dispatchDescribe',
        type: 'textarea',
      },
    ],
    rules: {
      acceptUserName: [
        {
          required: true,
          message: '请选择维修人员',
          trigger: 'change',
        },
      ],
    },
    labelWidth: '120px',
  },
})
//处理登记相关
const registerInfo = reactive({
  visible: false,
  title: '处理登记',
  btLoading: false,
  type: '',
  msg: '',
  width: '40%',
  flag: true,
  btList: [
    { label: '关闭', event: handleCloseRegister, show: true },
    {
      label: '保存',
      type: 'primary',
      event: saveRegister,
      show: true,
    },
  ],

  formInfo: {
    ref: null,
    data: {},
    fieldList: [
      {
        label: '处理人',
        value: 'dealUserName',
        type: 'input',
        disabled: true,
      },

      {
        label: '开始时间',
        value: 'startTime',
        type: 'slot',
        required: true,
      },
      {
        label: '结束时间',
        value: 'endTime',
        type: 'slot',
        required: true,
      },
      {
        label: '处理进度(%)',
        value: 'dealRate',
        type: 'number',
        precision: 2,
        max: 100,
        // required: true,
      },
      {
        label: '工作说明',
        value: 'dealDescribe',
        type: 'textarea',
        required: true,
      },
      {
        label: '附件',
        value: 'filePathList',
        type: 'slot',
        className: 'not-br',
      },
    ],
    rules: {
      startTime: [
        // {
        //   required: true,
        //   message: '请选择开始时间',
        //   trigger: 'change',
        // },
        {
          validator: validateStartTime,
          trigger: 'blur',
        },
      ],
      endTime: [
        // {
        //   required: true,
        //   message: '请选择结束时间',
        //   trigger: 'change',
        // },
        {
          validator: validateEndTime,
          trigger: 'blur',
        },
      ],
      dealDescribe: [
        {
          required: true,
          message: '请输入工作说明',
          trigger: 'blur',
        },
      ],
    },
    labelWidth: '110px',
  },
  uploadInfo: {
    action: axios.defaults.baseURL + '/pub/uploadfile',
    headers: {
      Authorization: proxy.$store.state.user.token,
    },
    loading: {},
    limit: 3,
    fileList: [],
    fileSize: proxy.$store.state.permission.systemConfig.max_file_size,
    fileType: [
      'png',
      'jpg',
      'jpeg',
      'pdf',
      'mp3',
      'm4a',
      'aac',
      'wav',
      'audio',
      'x-m4a',
      'doc',
      'docx',
      'xls',
      'xlsx',
    ],
  },
})
//完工相关
const finishInfo = reactive({
  visible: false,
  title: '完工',
  btLoading: false,
  type: '',
  msg: '',
  width: '40%',
  flag: true,
  btList: [
    { label: '关闭', event: handleCloseFinish, show: true },
    {
      label: '保存',
      type: 'primary',
      event: saveFinish,
      show: true,
    },
  ],

  formInfo: {
    ref: null,
    data: {},
    fieldList: [
      {
        label: '完工时间',
        value: 'completeTime',
        type: 'slot',
        required: true,
      },
      {
        label: '处理结果',
        value: 'dealResult',
        type: 'select-model',
        // clearable: true,
        code: 'deal_result',
        required: true,
      },
      {
        label: '合计工时(h)',
        value: 'dealTime',
        type: 'number',
        precision: 2,
        required: true,
      },
      {
        label: '维修服务费',
        value: 'serviceAmount',
        type: 'number',
        max: 999999999999999,
        formatter: proxy.$fn.TripartiteMethodAsset,
        precision:
          proxy.$store.state.permission.systemConfig.assets_price_precision,
      },
      {
        label: '维修材料费',
        value: 'materialAmount',
        type: 'number',
        max: 999999999999999,
        formatter: proxy.$fn.TripartiteMethodAsset,
        precision:
          proxy.$store.state.permission.systemConfig.assets_price_precision,
        disabled: true,
      },
      {
        label: '费用合计',
        value: 'sumAmount',
        type: 'number',
        disabled: true,
        max: 999999999999999,
        formatter: proxy.$fn.TripartiteMethodAsset,
        precision:
          proxy.$store.state.permission.systemConfig.assets_price_precision,
      },
      {
        label: '完工说明',
        value: 'dealDescribe',
        type: 'textarea',
        required: proxy.$store.state.permission.systemConfig.repair_complete_describe_required == 1,
      },
    ],
    rules: {
      completeTime: [
        // {
        //   required: true,
        //   message: '请选择完工时间',
        //   trigger: 'change',
        // },
        {
          validator: validateCompleteTime,
          trigger: 'blur',
        },
      ],
      dealTime: [
        {
          required: true,
          message: '请输入合计工时',
          trigger: 'blur',
        },
      ],
      dealDescribe: [
        {
          required: proxy.$store.state.permission.systemConfig.repair_complete_describe_required == 1,
          message: '请输入完工说明',
          trigger: 'blur',
        },
      ],
      completeDescribe: [
        {
          required: true,
          message: '请输入完工说明',
          trigger: 'blur',
        },
      ],
    },
    labelWidth: '120px',
  },
})
//故障确认相关
const faultVerifyInfo = reactive({
  visible: false,
  title: '故障确认',
  btLoading: false,
  type: '',
  msg: '',
  width: '40%',
  flag: true,
  btList: [
    { label: '关闭', event: handleCloseFaultVerify, show: true },
    {
      label: '保存',
      type: 'primary',
      event: saveFaultVerify,
      show: true,
    },
  ],

  formInfo: {
    ref: null,
    data: {},
    fieldList: [
      {
        label: '资产',
        value: 'assetName',
        type: 'input',
        required: true,
        disabled: true,
      },
      {
        label: '资产卡片号',
        value: 'assetCode',
        type: 'input',
        disabled: true,
      },
      {
        label: '故障发生时间',
        value: 'faultTime',
        type: 'slot',
      },

      {
        label: '停机时长(h)',
        value: 'haltTime',
        type: 'number',
        // precision: 1,
      },
      {
        label: '故障部位',
        value: 'faultPart',
        type: 'slot',
      },

      {
        label: '故障描述',
        value: 'faultDescribe',
        type: 'slot',
        required: true,
        maxlength: 500,
      },

      {
        label: '故障原因',
        value: 'faultReason',
        type: 'textarea',
        maxlength: 500,
      },
      {
        label: '维修方案',
        value: 'maintenanceScheme',
        type: 'slot',
        maxlength: 500,
      },
    ],
    rules: {
      assetName: [
        {
          required: true,
          message: '请输入资产',
          trigger: 'change',
        },
      ],
      faultTime: [
        {
          validator: validateFaultTime,
          trigger: 'blur',
        },
      ],
      faultDescribe: [
        {
          required: true,
          message: '请输入故障描述',
          trigger: 'blur',
        },
      ],
    },
    labelWidth: '120px',
  },
})
const selectAssetResourceInfo = ref({
  visible: false,
  query: {
    assetId: '',
  },
})
//配件使用相关
const mountingsUseInfo = reactive({
  orderId: '',
  maintenanceOrderId: '',
  visible: false,
  title: '配件使用',
  btLoading: false,
  type: '',
  msg: '',
  width: '75%',
  flag: true,
  btList: [
    {
      label: '关闭',
      event: handleCloseMountingsUse,
      show: true,
    },
    {
      label: '保存',
      type: 'primary',
      event: saveMountingsUse,
      show: true,
    },
  ],
  // 过滤相关配置
  filterInfo: {
    query: {
      customizeUserVO: {},
      queryMap: {},
    },
    list: [
      {
        label: '添加',
        type: 'button',
        event: addMountings,
        show: true,
      },
      {
        label: '删除',
        type: 'slot',
        value: 'removeMountings',
      },
    ],
  },
  // 表格相关
  tableInfo: {
    refresh: 1,
    initCurpage: 1,
    data: [],
    selections: [],
    api: getRepairPartsAffairPage,
    query: {
      maintenanceOrderId: props.id,
      sort: 'create_time desc',
    },
    fieldList: [
      {
        label: '配件名称',
        value: 'commonName',
      },
      {
        label: '规格',
        value: 'standard',
      },
      {
        label: '计量单位',
        value: 'unitName',
      },
      {
        label: '单价',
        value: 'price',
        type: 'slot',
        // type: "money",
        // max: 999999999999999,
        // formatter: proxy.$fn.TripartiteMethodAsset,
        // precision:
        //   proxy.$store.state.permission.systemConfig
        //     .assets_price_precision,
      },
      {
        label: '数量',
        value: 'qty',
        type: 'slot',

        // type: "number",
        // max: 999999999999999,
        // formatter: proxy.$fn.TripartiteMethodAsset,
        // precision:
        //   proxy.$store.state.permission.systemConfig
        //     .assets_price_precision,
      },
      {
        label: '金额',
        value: 'sumAmount',
        max: 999999999999999,
        formatter: proxy.$fn.TripartiteMethodAsset,
        // precision:
        //   proxy.$store.state.permission.systemConfig
        //     .assets_price_precision,
      },
      {
        label: '更换日期',
        value: 'useTime',
        type: 'slot',
      },
    ],
    handle: {
      fixed: 'right',
      label: '操作',
      width: '50',
      btList: [
        {
          label: '删除',
          event: removeMountings,
          popconfirmText: '删除后将改变数据,是否继续？',
          show: true,
        },
      ],
    },
  },
})
//选择维修人员
const selectRepairUserInfo = reactive({
  visible: false,
  saveEmpty: true,
  api: getSelectUserWithPermission,
  query: {
    orgId: '',
    assetId: '',
    deptId: '',
    depotId: '',
    assetClassifyId: '',
    notAssetRepairType: '',
  },
})
//选择配件
const accessoriesInfo = reactive({
  visible: false,
  query: {
    id: {
      queryType: 'NOT_IN',
      queryCategory: 'AND',
      value: '',
    },
  },
})
//选择报修单
const repairOrderInfo = reactive({
  visible: false,
  query: {
    // status:1
  },
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})

const canReceiveOrder = computed(() => {
  const canReceiveUserArr = baseInfoList.data.pendReceiveUser
    ? baseInfoList.data.pendReceiveUser.split(',')
    : []
  const currentUser = proxy.$store.state.user.userInfo.user.id
  const userType = proxy.$store.state.user.userInfo.user.type
  return (
    proxy.$permission('maintenanceOrder:receiveOrder') &&
    baseInfoList.data.status === 1 &&
    baseInfoList.data.orderSource !== 2 &&
    ((baseInfoList.data.maintenanceUser &&
      baseInfoList.data.maintenanceUser === -2 &&
      canReceiveUserArr.includes(currentUser + '')) ||
      (canReceiveUserArr.length === 0 && assetSourceAuth.value) ||
      userType !== 'normal')
  )
})
const canTurnOver = computed(() => {
  return (
    proxy.$permission('maintenanceOrder:turnOver') &&
    baseInfoList.data.status === 2 &&
    baseInfoList.data.orderSource !== 2 &&
    ((baseInfoList.data.maintenanceUser &&
      baseInfoList.data.maintenanceUser === -2 &&
      assetSourceAuth.value) ||
      baseInfoList.data.maintenanceUser ===
        proxy.$store.state.user.userInfo.user.id ||
      proxy.$store.state.user.userInfo.user.type !== 'normal')
  )
})
const canFaultVerify = computed(() => {
  return (
    proxy.$permission('maintenanceOrder:faultVerify') &&
    baseInfoList.data.status === 2 &&
    baseInfoList.data.orderSource !== 2 &&
    ((baseInfoList.data.maintenanceUser &&
      baseInfoList.data.maintenanceUser === -2 &&
      assetSourceAuth.value) ||
      baseInfoList.data.maintenanceUser ===
        proxy.$store.state.user.userInfo.user.id ||
      proxy.$store.state.user.userInfo.user.type !== 'normal')
  )
})
const canMountingsUse = computed(() => {
  return (
    proxy.$permission('maintenanceOrder:mountingsUse') &&
    baseInfoList.data.status === 2 &&
    baseInfoList.data.orderSource !== 2 &&
    ((baseInfoList.data.maintenanceUser &&
      baseInfoList.data.maintenanceUser === -2 &&
      assetSourceAuth.value) ||
      baseInfoList.data.maintenanceUser ===
        proxy.$store.state.user.userInfo.user.id ||
      proxy.$store.state.user.userInfo.user.type !== 'normal')
  )
})
const canHandleRegister = computed(() => {
  return (
    proxy.$permission('maintenanceOrder:handleRegister') &&
    baseInfoList.data.status === 2 &&
    baseInfoList.data.orderSource !== 2 &&
    ((baseInfoList.data.maintenanceUser &&
      baseInfoList.data.maintenanceUser === -2 &&
      assetSourceAuth.value) ||
      baseInfoList.data.maintenanceUser ===
        proxy.$store.state.user.userInfo.user.id ||
      proxy.$store.state.user.userInfo.user.type !== 'normal')
  )
})
const canFinish = computed(() => {
  return (
    proxy.$permission('maintenanceOrder:finish') &&
    baseInfoList.data.status === 2 &&
    baseInfoList.data.orderSource !== 2 &&
    ((baseInfoList.data.maintenanceUser &&
      baseInfoList.data.maintenanceUser === -2 &&
      assetSourceAuth.value) ||
      baseInfoList.data.maintenanceUser ===
        proxy.$store.state.user.userInfo.user.id ||
      proxy.$store.state.user.userInfo.user.type !== 'normal')
  )
})
const canCancelFinish = computed(() => {
  return (
    proxy.$permission('maintenanceOrder:cancelFinish') &&
    baseInfoList.data.status === 3 &&
    baseInfoList.data.orderSource !== 2 &&
    ((baseInfoList.data.maintenanceUser &&
      baseInfoList.data.maintenanceUser === -2 &&
      assetSourceAuth.value) ||
      baseInfoList.data.maintenanceUser ===
        proxy.$store.state.user.userInfo.user.id ||
      proxy.$store.state.user.userInfo.user.type !== 'normal')
  )
})

watch(
  () => props.visible,
  (newVal) => {
    showDialog.value = newVal
  },
  {
    immediate: true,
  }
)

watch(
  () => props.id,
  (newVal) => {
    filterInfo.query.productId = newVal
    mountingsUseInfo.tableInfo.query.maintenanceOrderId = newVal
    affairTableInfo.query.orderId = newVal
    customFilterInfo.query.queryMap.id.value = newVal
    mountingsUseTableInfo.query.maintenanceOrderId = newVal
    finishTableInfo.query.maintenanceId = newVal
    getDetails()
  },
  {
    immediate: true,
    deep: true,
  }
)
watch(
  () => mountingsUseInfo.tableInfo.data,
  (val) => {
    if (val.length) {
      let ids = []
      val.forEach((row) => {
        ids.push(row.productId)
      })
      accessoriesInfo.query.id.value = String(ids)
      if (proxy.$refs.mountingsUseTable) {
        proxy.$refs.mountingsUseTable.setListInfoTotal(val.length)
      }
    } else {
      accessoriesInfo.query.id.value = ''
      if (proxy.$refs.mountingsUseTable) {
        proxy.$refs.mountingsUseTable.setListInfoTotal(0)
      }
    }
  },
  {
    deep: true,
  }
)
watch(
  () => finishInfo.formInfo.data,
  (val) => {
    let materialAmount = val.materialAmount || 0
    let serviceAmount = val.serviceAmount || 0
    val.sumAmount = proxy.$fn.accAdd(serviceAmount, materialAmount)
  },
  {
    deep: true,
  }
)

function validateUseTime(rule, value, callback) {
  let currentTime = moment(new Date()).format('YYYY-MM-DD')
  let updateTime = moment(value).format('YYYY-MM-DD')
  if (updateTime > currentTime) {
    callback(new Error('更换日期不能大于当前日期！'))
  } else {
    callback()
  }
}

function selectMountingsTable(event, data) {
  switch (event) {
    case 'tableCheck':
      mountingsUseInfo.tableInfo.selections = [...data]
      break
  }
}
//单价
function changePrice(e, row, str) {
  if (str === 'qty') {
    row.sumAmount = proxy.$fn.accMul(e, row.price)
    // row.sumAmount = proxy.$fn.TripartiteMethodAsset(e * row.price);
  } else if (str === 'price') {
    row.sumAmount = proxy.$fn.accMul(e, row.qty)
    // row.price = e;
    // row.sumAmount = proxy.$fn.TripartiteMethodAsset(e * row.qty);
  }
}
//删除附件
function uploadRemove(file, fileList) {
  registerInfo.formInfo.data.filePathList = fileList
}
function handleExceed() {
  proxy.$message.warning(` 只能上传 ${registerInfo.uploadInfo.limit} 个文件`)
}
function beforeProductUpload(file) {
  //验证文件格式
  let fileTypeArr = file.name.split('.')[file.name.split('.').length - 1]
  if (registerInfo.uploadInfo.fileType.indexOf(fileTypeArr) === -1) {
    proxy.$message.error(
      `文件格式不正确, 请上传 ${registerInfo.uploadInfo.fileType.join(
        ' / '
      )} 格式文件!`
    )
    return false
  }
  let file_type_list = proxy.$store.state.permission.dict['file_type_list']
  if (file_type_list && file_type_list.length) {
    let uploadType = file.name.split('.')[file.name.split('.').length - 1]
    let file_type_list_arr = []
    file_type_list.forEach((item) => {
      file_type_list_arr.push(item.code)
    })
    if (!String(file_type_list_arr).includes(uploadType)) {
      proxy.$message.error({
        message: `文件格式【${uploadType}】非白名单文件类型格式，不支持上传`,
        showClose: true,
        duration: 3500,
      })
      return false
    }
  }
  //验证文件大小
  const maxFileSize = file.size / 1024 / 1024 < registerInfo.uploadInfo.fileSize
  if (!maxFileSize) {
    proxy.$message.error(
      `上传文件大小不能超过${registerInfo.uploadInfo.fileSize}Mb！`
    )
    return false
  }
  //发生请求时打开加载动画
  registerInfo.uploadInfo.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })
  return true
}
//上传附件
function uploadAttachment(resp, file, fileList) {
  registerInfo.uploadInfo.loading.close()
  if (resp && resp.success) {
    file.filePath = resp.data[0]
    registerInfo.formInfo.data.filePathList = fileList
  }
}
function uploadError(err) {
  if (err) {
    ElMessage.error({
      message: '系统错误',
      duration: 3000,
      showClose: true,
    })
  }
  registerInfo.uploadInfo.loading.close()
}
function openAssetResource() {
  selectAssetResourceInfo.value.visible = true
  selectAssetResourceInfo.value.query.assetId =
    faultVerifyInfo.formInfo.data['assetId']
}
function SelectAssetResourceCallBack(data) {
  if (data && data.length) {
    let resourceName = data.map((item) => item.resourceName)
    faultVerifyInfo.formInfo.data.faultPart =
      resourceName && resourceName.length ? resourceName.toString() : ''
  } else {
    faultVerifyInfo.formInfo.data.faultPart = ''
  }
}
function openRepairUserWindow() {
  selectRepairUserInfo.visible = true
}
function selectRepairUserCallBack(row) {
  if (row) {
    turnOverInfo.formInfo.data['acceptUser'] = row.userId
    turnOverInfo.formInfo.data['acceptUserName'] = row.name
  } else {
    turnOverInfo.formInfo.data['acceptUser'] = ''
    turnOverInfo.formInfo.data['acceptUserName'] = ''
  }
}

function handleCloseMountingsUse() {
  mountingsUseInfo.visible = false
}
function handleCloseFaultVerify() {
  faultVerifyInfo.visible = false
}
function handleCloseRegister() {
  registerInfo.visible = false
}
function handleCloseFinish() {
  finishInfo.visible = false
}
function handleCloseTurnOver() {
  turnOverInfo.visible = false
}

//接单
function receiveOrder() {
  if (
    (baseInfoList.data.maintenanceUser &&
      baseInfoList.data.maintenanceUser === -2) ||
    baseInfoList.data.maintenanceUser ===
      proxy.$store.state.user.userInfo.user.id ||
    proxy.$store.state.user.userInfo.user.type !== 'normal'
  ) {
    acceptMaintenceOrder(baseInfoList.data.id).then((resp) => {
      if (resp && resp.success) {
        getDetails()
      }
    })
  } else {
    proxy.$message.warning('当前用户不是该单据的维修人，不可操作该单据！')
  }
}
//转交
function turnOver() {
  if (
    (baseInfoList.data.maintenanceUser &&
      baseInfoList.data.maintenanceUser === -2) ||
    baseInfoList.data.maintenanceUser ===
      proxy.$store.state.user.userInfo.user.id ||
    proxy.$store.state.user.userInfo.user.type !== 'normal'
  ) {
    turnOverInfo.formInfo.data = {}
    turnOverInfo.visible = true
    turnOverInfo.title = '转交'
    turnOverInfo.formInfo.data.orderId = baseInfoList.data.id
    turnOverInfo.formInfo.data.orderType = 54
    selectRepairUserInfo.query.orgId =
      baseInfoList.data.maintenanceId === -2
        ? ''
        : baseInfoList.data.maintenanceId
    selectRepairUserInfo.query.assetId =
      baseInfoList.data.assetId === -2 ? '' : baseInfoList.data.assetId
    selectRepairUserInfo.query.deptId =
      baseInfoList.data.useDeptId === -2 ? '' : baseInfoList.data.useDeptId
    selectRepairUserInfo.query.depotId =
      baseInfoList.data.depotId === -2 ? '' : baseInfoList.data.depotId
    selectRepairUserInfo.query.assetClassifyId =
      baseInfoList.data.classifyType === -2
        ? ''
        : baseInfoList.data.classifyType
    selectRepairUserInfo.query.notAssetRepairType =
      baseInfoList.data.notAssetRepairType === -2
        ? ''
        : baseInfoList.data.notAssetRepairType

    selectRepairUserInfo.query.userIdNotIn = baseInfoList.data.maintenanceUser
    proxy.$nextTick(() => {
      turnOverInfo.formInfo.ref.clearValidate()
    })
  } else {
    proxy.$message.warning('当前用户不是该单据的维修人，不可操作该单据！')
  }
}

//转交保存
function saveTurnOver() {
  turnOverInfo.formInfo.ref.validate((valid) => {
    if (valid) {
      passOnMaintenceOrder(turnOverInfo.formInfo.data).then((resp) => {
        if (resp && resp.success) {
          getDetails()
        }
      })
      turnOverInfo.visible = false
    }
  })
}
//处理登记
function handleRegister() {
  if (proxy.$store.state.user.userInfo.user.type === 'normal') {
    if (
      baseInfoList.data.maintenanceUser !=
      proxy.$store.state.user.userInfo.user.id
    ) {
      proxy.$message.warning('当前登录人员不是该维修单据的维修人员！')
      return
    }
  }
  registerInfo.formInfo.data = {}
  registerInfo.visible = true
  registerInfo.formInfo.data.dealUser = proxy.$store.state.user.userInfo.user.id
    ? proxy.$store.state.user.userInfo.user.id
    : ''
  registerInfo.formInfo.data.dealUserName = proxy.$store.state.user.userInfo
    .user.name
    ? proxy.$store.state.user.userInfo.user.name
    : ''
  registerInfo.formInfo.data.orderId = baseInfoList.data.repairId
  registerInfo.formInfo.data.filePathList = []
  registerInfo.uploadInfo.fileList = []
  registerInfo.formInfo.data.orderType = 54
  registerInfo.formInfo.data.maintenanceOrderId = props.id
  proxy.$nextTick(() => {
    registerInfo.formInfo.ref.clearValidate()
  })
}
//处理登记保存
function saveRegister() {
  registerInfo.formInfo.ref.validate((valid) => {
    if (valid) {
      repairDealAffair(registerInfo.formInfo.data).then((resp) => {
        if (resp && resp.success) {
          getDetails()
        }
        registerInfo.visible = false
      })
    }
  })
}
//完工
function finish() {
  summaryWorkingHours({
    orderId: baseInfoList.data.repairId,
    orderType: 54,
  }).then((res) => {
    if (res && res.success) {
      finishInfo.formInfo.data.dealTime = res.data
    }
  })
  finishInfo.formInfo.data = {
    completeTime: moment(new Date()).format('YYYY-MM-DD HH:mm'),
  }
  finishInfo.visible = true
  finishInfo.formInfo.data.id = baseInfoList.data.id
  finishInfo.formInfo.data.serviceAmount = baseInfoList.data.serviceAmount
  finishInfo.formInfo.data.materialAmount = baseInfoList.data.materialAmount
  proxy.$nextTick(() => {
    finishInfo.formInfo.ref.clearValidate()
  })
}

//完工保存
function saveFinish() {
  finishInfo.formInfo.ref.validate((valid) => {
    if (valid) {
      dealCompleteMaintenceOrder(finishInfo.formInfo.data).then((resp) => {
        if (resp && resp.success) {
          getDetails()
        }
        finishInfo.visible = false
      })
    }
  })
}
//取消完工
function cancelFinish() {
  cannelMaintenceOrder(baseInfoList.data.id).then((resp) => {
    if (resp && resp.success) {
      getDetails()
    }
  })
}
//故障确认
function faultVerify() {
  if (proxy.$store.state.user.userInfo.user.type === 'normal') {
    if (
      baseInfoList.data.maintenanceUser !=
      proxy.$store.state.user.userInfo.user.id
    ) {
      proxy.$message.warning('当前登录人员不是该维修单据的维修人员！')
      return
    }
  }
  let row = baseInfoList.data
  faultVerifyInfo.formInfo.data = {}
  faultVerifyInfo.visible = true
  faultVerifyInfo.formInfo.data.id = row.id
  faultVerifyInfo.formInfo.data['faultTime'] = row.faultTime
  faultVerifyInfo.formInfo.data['haltTime'] = row.haltTime
  faultVerifyInfo.formInfo.data['faultReason'] = row.faultReason
  faultVerifyInfo.formInfo.data['faultPart'] = row.faultPart
  faultVerifyInfo.formInfo.data['faultDescribe'] = row.faultDescribe
  faultVerifyInfo.formInfo.data['maintenanceScheme'] = row.maintenanceScheme
  faultVerifyInfo.formInfo.data['assetName'] = row.assetName
  faultVerifyInfo.formInfo.data['assetCode'] = row.assetCode
  faultVerifyInfo.formInfo.data['assetId'] = row.assetId
  faultVerifyInfo.formInfo.data['faultLibraryId'] = row.faultLibraryId
  clickItem.value = row
  proxy.$nextTick(() => {
    faultVerifyInfo.formInfo.ref.clearValidate()
  })
}
//故障确认保存
function saveFaultVerify() {
  faultVerifyInfo.formInfo.ref.validate((valid) => {
    if (valid) {
      faultConfirmMaintenceOrder(faultVerifyInfo.formInfo.data).then((resp) => {
        if (resp && resp.success) {
          getDetails()
        }
        faultVerifyInfo.visible = false
      })
    }
  })
}
//配件使用
function mountingsUse() {
  if (proxy.$store.state.user.userInfo.user.type === 'normal') {
    if (
      baseInfoList.data.maintenanceUser !=
      proxy.$store.state.user.userInfo.user.id
    ) {
      proxy.$message.warning('当前登录人员不是该维修单据的维修人员！')
      return
    }
  }
  let row = baseInfoList.data
  mountingsUseInfo.visible = true
  mountingsUseInfo.tableInfo.data = []
  mountingsUseInfo.orderId = row.repairId
  mountingsUseInfo.maintenanceOrderId = row.id

  mountingsUseInfo.tableInfo.refresh = Math.random()
  setTimeout(() => {
    getMountingsUseList()
  }, 0)
}
//添加配件
function addMountings() {
  accessoriesInfo.visible = true
}
function getMountingsUseList() {
  mountingsUseInfo.tableInfo.refresh = Math.random()
}
//删除配件
function removeMountings(row = undefined) {
  if (row) {
    mountingsUseInfo.tableInfo.data = mountingsUseInfo.tableInfo.data.filter(
      (item) => item.productId !== row.productId
    )
  } else {
    mountingsUseInfo.tableInfo.data = mountingsUseInfo.tableInfo.data.filter(
      (item) => {
        return !mountingsUseInfo.tableInfo.selections.includes(item)
      }
    )
  }
}
//选择配件
function changeAccessories(data) {
  if (data.length) {
    data.forEach((item) => {
      let obj = {
        productId: item.id,
        productName: item.commonName,
        price: item.referencePrice,
        ...item,
        useTime:
          item.useTime || moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
      }
      mountingsUseInfo.tableInfo.data.push(obj)
    })
    accessoriesInfo.visible = false
  }
}
//配件使用保存
function saveMountingsUse() {
  let data = mountingsUseInfo.tableInfo.data
  if (data.length) {
    proxy.$refs['tableForm'].validate((valid) => {
      if (valid) {
        let arr = []

        data.forEach((item) => {
          arr.push({
            commonName: item.commonName,
            productCode: item.productCode,
            unitName: item.unitName,
            standard: item.standard,
            productId: item.productId,
            calcQty: item.qty,
            qty: item.qty,
            orderId: mountingsUseInfo.orderId,
            orderType: 54,
            price: item.price,
            sumAmount: item.sumAmount,
            useTime: item.useTime,
            maintenanceOrderId: baseInfoList.data.id,
            maintenanceNo: baseInfoList.data.orderNo,
            repairId: baseInfoList.data.repairId,
            repairNo: baseInfoList.data.repairNo,
          })
        })
        createRepairPartsAffair(arr).then((resp) => {
          if (resp && resp.success) {
            getDetails()
          }
          mountingsUseInfo.visible = false
        })
      }
    })
  } else {
    delByMaintenanceIdRepairPartsAffair(props.id).then((resp) => {
      if (resp && resp.success) {
        getDetails()
      }
      mountingsUseInfo.visible = false
    })
  }
}
function handleClick(tab) {
  const name = tab.paneName
  if (name == 'first') {
    getDealList()
  } else if (name == 'second') {
    getMountingsUseTableList()
  } else if (name == 'third') {
    getFinishTableList()
  }
}
function handleTabClick(tab) {
  const name = tab.paneName
  if (name == 'second') {
    getRepairList()
  } else if (name == 'third') {
    getAffairList()
  }
}
function getRepairList() {
  getRepairOrderById(baseInfoList.data.repairId).then((resp) => {
    if (resp && resp.success) {
      repairInfoList.data = resp.data
      if (resp.data.assetStatus === 1) {
        showFieldListItem(true, 'useDeptName')
        showFieldListItem(false, 'depotName')
      } else if (resp.data.assetStatus === 3) {
        showFieldListItem(false, 'useDeptName')
        showFieldListItem(true, 'depotName')
      }
    }
  })
}
function showFieldListItem(show, nameValue) {
  let fieldList = repairInfoList.fieldList
  fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.show = show
    }
  })
}
function modifyCallback() {
  getDetails()
}
function returnFinanceModifyInfo() {
  getDetails()
}
function returnBack() {
  emit('returnBack', false)
}

// 获取列表
function getList() {
  mountingsUseInfo.tableInfo.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  mountingsUseInfo.tableInfo.initCurpage = Math.random()
  mountingsUseInfo.tableInfo.refresh = Math.random()
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      mountingsUseInfo.tableInfo.selections = [...data]
      break
  }
}
function getDealList() {
  dealInfo.refresh = Math.random()
}
function getAffairList() {
  orderOpAffairAll(affairTableInfo.query).then((resp) => {
    if (resp && resp.success) {
      affairTableInfo.data = resp.data
    }
  })
}
function getMountingsUseTableList() {
  mountingsUseTableInfo.refresh = Math.random()
}

function getFinishTableList() {
  finishTableInfo.refresh = Math.random()
}

function getDetails() {
  getMaintenceOrderById(props.id).then((resp) => {
    if (resp && resp.success) {
      baseInfoList.data = resp.data
      faultInfoList.data = resp.data
      finishInfoList.data = resp.data
      sendOrderInfoList.data = resp.data
      basicInfoList.data = resp.data
      dealInfo.query.orderId = resp.data.repairId
      if (baseInfoList.data.maintenanceUser === -2) {
        getMaintenceOrderList(baseInfoList.data.orderNo)
      }
      getDealList()
      getMountingsUseTableList()
      getAffairList()
      getRepairList()
    }
  })
}
function getMaintenceOrderList(orderNo) {
  //用户无维修权限，只有查看权限
  let param = {
    tableKey:
      'repairMaintenceOrderList-com.slip.spd.entity.vo.repair.MaintenanceOrderVO',
  }
  let query = {
    sortString: '',
    customizeUserVO: {},
    queryMap: {
      assetSourceAuth: {
        asTbName: 'repair_order,repair_order',
        columnName: 'use_dept_id,depot_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'assetSourceAuth',
      },
      orderNo: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: orderNo,
      },
    },
    queryParams: {},
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      query.customizeUserVO = data

      getMaintenceOrderCustomizeListAll(query).then((res) => {
        if (res && res.success && res.data && res.data.length) {
          assetSourceAuth.value = true
        }
      })
    }
  })
}

// 故障库
function openFault() {
  console.log(clickItem.value)
  seelctFault.value.visible = true
  seelctFault.value.query['repairTypeMult'] = clickItem.value.repairType
  seelctFault.value.query['classifyTypeMult'] = clickItem.value.classifyType
  seelctFault.value.query['classifyTypeValue'] =
    clickItem.value.classifyTypeValue
  seelctFault.value.query['notAssetRepairTypeMult'] =
    clickItem.value.notAssetRepairType
}

function selectFaultCallback(row) {
  console.log(row)
  faultVerifyInfo.formInfo.data.faultDescribe = row.faultDescribe
  faultVerifyInfo.formInfo.data.faultReason = row.faultReason
  faultVerifyInfo.formInfo.data.maintenanceScheme = row.maintenanceScheme
  faultVerifyInfo.formInfo.data.faultLibraryId = row.id
}
function addFaultCallback(row) {
  console.log(row)
}

function _addFault() {
  console.log(clickItem.value)
  tableDialogInfo.value.visible = true
  tableDialogInfo.value.type = 'update'
  tableDialogInfo.value.data = {
    ...clickItem.value,
    ...faultVerifyInfo.formInfo.data,
  }
}
</script>
<style scoped lang="scss">
:deep(.el-tabs__header) {
  padding: 0 2px !important;
  box-sizing: border-box;
}

:deep(.el-tabs__nav-wrap::after) {
  height: 1px !important;
}
.model-panel-left {
  width: 73%;
  float: left;
  margin-right: 10px;
}
.model-panel-right {
  width: 25%;
}
</style>
